<?php
echo $javascript->link(array( 'tag-option/jquery.optionTree'));
echo $this->Html->css(array('autocomplete/subject/style', 'autocomplete/token-input-facebook', 'autocomplete/token-input'));
?>
<style type="text/css">
    select.vertical {
        display: block;
    }

</style>
<script type="text/javascript">
    $(document).ready(function() {
       var base_url=$('#base-url').text(); // This will be used for all ajax calls as base url
       var options = {
            empty_value:null,
            indexed: true,  // the data in tree is indexed by values (ids), not by labels
            on_each_change:base_url+ '/Homes/tags', // this file will be called with 'id' parameter, JSON data must be returned
            choose: function(level) {
                return 'Choose level ' + level;
            },
            loading_image: base_url+'/app/webroot/img/ajax-load.gif',
            show_multiple: false, // if true - will set the size to show all options
            choose: '' // no choose item
        };

        var displayParents = function() {
            var labels = []; // initialize array
            $(this).siblings('select') // find all select
            .find(':selected') // and their current options
            .each(function() { labels.push($(this).text()); }); // and add option text to array
            // $("<div >").html( labels.join(' > ')+"<a class='delete' href='#'> X</a>").appendTo('#demo7-result');  // and display the labels
            if($(this).find(':selected').value!='0'){
                $('#demo7-result').css("background-color","#01303F");
                $('#demo7-result').css("border","1px solid #0B4557");
                $('#demo7-result').css("line-height","14px");
                $('#demo7-result').css("font-size","11px");
                $('#demo7-result').css("margin","3px 0 0");
                $('#demo7-result').css("padding","3px");
                $('#demo7-result').css("float","left");
                $('#demo7-result').css("width","450px");
                $('#demo7-result').html($('<div class="tag_name">').text( labels.join(' > '))); 
                //$('#demo7-result').html($('<div >').text( labels.join(' >')));  //commented on 2 sept
            }
        }
  
        $.getJSON(base_url+'/Homes/tags?id=2', function(tree) { // initialize the tree by loading the file first
            $('input[id=demo7]').optionTree(tree, options).change(displayParents);
        
        
        
        });
        
       
 
        $('#more ').live('click',function(){
          
            //alert($('div[id|="#tag"').bind(length));
            //alert($('input[id=demo7]').lenght);
            if($('input[id=demo7]').val()!='' && $('#demo7-result').html()!=''){
                $('#tagpool').append('<div id="'+$('input[id=demo7]').val()+'" class="tag_container">'+$('#demo7-result').html()+"<div class='remove_tag'>X</div><div class='edit_tag'>Edit</div><input type='hidden' name='tag_ids[]' value='"+$('input[id=demo7]').val()+"'/></div>");
                $('#tagpool').append($('#attributes').html());
                $(".tagwrapper").css("background","none");
                $(".tagwrapper").css("border","1px solid #063F52");
                $("#attributes").empty();
                $('#error-message').empty();
                $("#attributes").css("background","");
                $("#attributes").css("border","");
                $("#demo7-result").empty();
                $('#demo7-result').css("background-color","");
                $('#demo7-result').css("border","none");
                $.getJSON(base_url+'/Homes/tags?id=2', function(tree) { // initialize the tree by loading the file first
                    $('input[id=demo7]').optionTree(tree, options).change(displayParents);
                });
            }
            //$('#tag_values').html($('#tag_values').html()+','+$('#demo7').val());
            $(".remove_tag").bind('click',function(){
                //alert($($($(this).prev()).parent()).attr("id"));
                var currentID=$($(this).prev().parent()).attr("id");
                //alert(currentID);
                $('#'+currentID).remove();
            
             
            });
        });
        
        /*********************** Edit tag chain   **********************/
       
        $(".edit_tag").live('click',function(){
            //alert($($($(this).prev()).parent()).attr("id"));
            var currentID=$($(this).parent()).attr("id");
            //alert($('#'+currentID).remove().html());
            $('#demo7-result').append($('#'+currentID).remove().html());
            //$('#'+currentID).remove();
            
            
            $.ajax({
                url: base_url+"/Homes/tag",
                global: false,
                type: "POST",
                data: {id : currentID },
                dataType: "html",
                async:false,
                success: function(response){
                    x=response;
                           
                }
            }
        );
            //alert(currentID);  
            var t=x.split(',');
            var options = {
                empty_value: null,
                indexed: true,  // the data in tree is indexed by values (ids), not by labels
                on_each_change: base_url+'/Homes/tags', // this file will be called with 'id' parameter, JSON data must be returned
                choose:'',
                preselect: {'data[Subject][tag_ids]':t}
            };

            var displayParents = function() {
                var labels = []; // initialize array
                $(this).siblings('select') // find all select
                .find(':selected') // and their current options
                .each(function() { labels.push($(this).text()); }); // and add option text to array
                $('<div>').text(this.value + ':' + labels.join(' > ')).appendTo('#demo5-result');  // and display the labels
            }

            $.getJSON(base_url+'/Homes/tags', function(tree) { // initialize the tree by loading the file first
                $('#demo7').optionTree(tree, options).change(displayParents);
                
            });
            var checkpool=$('#tagpool').html();
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
            if(checkpool==''){
                $(".tagwrapper").css("background","");
                $(".tagwrapper").css("border","");
            }
            
        });
        
        
        /*********************Edit Tag ends**********************/
         
         
    });
   $( "#new-small-slider-range-min .ui-slider-handle" ).html('0')
    $( "#new-small-slider-range-min" ).slider({
			range: "min",
			value:0,
			min: 0,
			max: 100,
                        
                        slide: function( event, ui ) {
                          $( "#new-smaill-amount" ).val(ui.value );
                          $( ".ui-slider-handle" ).html(ui.value );
                          $(ui.value).each(function(){
                            pindex=10
                            if(ui.value%5=='0' && ui.value!='100'){
                                pindex=-(ui.value*4);
                                //alert(ui.value);
                                 $('.ui-slider-handle').css('background-position',pindex+'px 0');
                        
                            }
                    
                        });
                      }
                        
		});
		$( ".ui-slider-handle" ).html($( ".slider-range-min" ).slider( "value" ) );
</script>

<p id="searchresults">
<?php

		if(isset($_POST['queryString'])) {
			$queryString = mysql_real_escape_string($_POST['queryString']);
			
			// Is the string length greater than 0?
			if(strlen($queryString) >0) {
				$query = mysql_query("SELECT * FROM subject  WHERE subject LIKE '%" . $queryString . "%' OR redirects  LIKE '%" . $queryString . "%' AND `status`='1' AND `17+`='0' ORDER BY id LIMIT 5") or die(mysql_error());
				
				if($query) {
					// While there are results loop through them - fetching an Object.
					
					// Store the category id
					$subject_id = 0;
					while ($result = mysql_fetch_array($query)) {
	         			    $thumbnail = $this->PhpThumb->generate(
                                            array(
                                            'save_path' => WWW_ROOT . 'img/uploads/Subjects/thumbs',
                                            'display_path' => 'uploads/Subjects/thumbs',
                                            'error_image_path' => 'error.png',
                                            'src' => WWW_ROOT . "img/uploads/Subjects/".$result['image'],
                                            'w' => 46,
                                            'h' => 46,
                                            'q' => 100,
                                            'zc' => 1
                                            )
                                        );
                                       
                                           ?>
                                           
                                        <a href="<?php echo $this->base.'/Subjects/subject/'.$result['id']; ?>"><img src="<?php echo $this->base . '/img/'.$thumbnail['src']; ?>" class="lastest_img" width="<?php echo $thumbnail['w']; ?>" height="<?php echo $thumbnail['h']; ?>" title="<?php echo $result['subject']; ?>"/>
                                        <?php
                                       if($result['id']!= $subject_id) { 
                                           if($result['redirects']!=""){
                                              $res=explode(',', $result['redirects']);
                                              $i=0;
                                             // echo $queryString;
                                              foreach($res as $ress){
                                                  echo strstr($ress,$queryString);
                                               }
							
                                           }else{
                                               echo '<b>'.$result['subject'].'</b><br/>';
                                           }        
							$catid = $result['id'];
					}		
	         			$description = $result['desc'];
	         			if(strlen($description) > 100) { 
	         				$description = substr($description, 0, 100) . "...";
	         			}
	         			
	         			echo '<span>'.$description.'</span></a>';
	         		}
	         		echo '<span class="seperator"><a href="#searchrating" id="autosearch" title="Sitemap">If Found Nothing ? Add Your Own Subject</a></span><br class="break" />';
				} else {
					echo 'ERROR: There was a problem with the query.';
				}
			} else {
				// Dont do anything.
			} // There is a queryString.
		} else {
			echo 'There should be no direct access to this script!';
		
                }
	
?>
</p>

<div id="popup_container" style="display:none;">
        <div id="searchrating" class="rate" style="">
        <?php echo $this->Form->create('Subject',array('action'=>'add','type'=>'file','id'=>'SubjectSearchRateForm','style'=>'width:610px;'));
        echo $this->Form->input('id',array('type'=>'hidden','id'=>'rated_subject'))
        ?>    
        
              <table cellspacing="0" width="100%" cellpadding="0" border="0" >
                <tbody>
                  <tr>
                      <td colspan="2"><h2>ADD NEW RATE</h2></td>
                  </tr>
                  
                   <tr>
                     <td width="25%"><b>Suggested Named</b></td><td><?php echo $this->Form->input('Subject.subject',array('label'=>'','id'=>'subjectname','type'=>'text','title'=>'Adjective','class'=>'input2')) ?><div id="subjecterror"></div></td>
                  </tr>
                   <tr>
                      <td width="25%"><b>Specify Word</b></td><td><?php echo $this->Form->input('Subject.desc',array('label'=>'','id'=>'specifier','type'=>'text','title'=>'Adjective','value'=>'','class'=>'input2')) ?></td>
                  </tr>
                  <tr>
                    <td width="25%">&nbsp;</td> <td width="75%" colspan="2" align="left">
                        <div class="meter-div1">
                       <div id="new-small-slider-range-min"> </div>
                      </div>
                        <input type="hidden" id="new-smaill-amount" name="rating"  style="border:0; color:#f6931f; font-weight:bold;" />
                    </td>
                  </tr><tr><td>&nbsp;</td><td><div id="tagpool" style="background-color: #000;float: left" class="tagwrapper"></div></td></tr>
                   <tr>
                       <td width="25%"><b>Tags</b></td> <td width="75%" colspan="2"><div class="select-tag"><?php echo $this->Form->input('Subject.tag_ids', array('label' => '', 'id' => 'demo7', 'type' => 'hidden')); ?><span id="more" class="mybutton"><a href="#">Save</a></span><div id="error-message" class="error-message"></div><div id="tag_values"></div></div>
            <div class="results" id="demo7-result"><div  id="attributes"></div></div>  </td>
                          
                   </tr> <tr><td>&nbsp;</td></tr>
                   <tr>
                         <td id="label" >Image<span class="required_field">*</span></td>
                         <td><?php  echo $this->Form->input('Subject.image', array('label' => '', 'type' => 'file', 'id' => 'image')); ?><div id="missing_image" class="error-message"></div></td>
                    </tr>  
                  <tr>
                    <td width="25%">&nbsp;</td> <td colspan="2"><h3>Add One, Two, or Three Adjectives (optional)</h3></td>
                  </tr>
                  <tr>
                   <td width="25%">&nbsp;</td>  <td colspan="2"><?php 
                   //echo $this->Form->input('Subject.adjective_ids', array('label' => '','type'=>'hidden'));
                   echo $this->Form->input('Subject.adjective_ids',array('label'=>'','id'=>'newadjective1','type'=>'text','title'=>'Adjective','class'=>'input2')) ?></td>
                <script type="text/javascript">
                    $(document).ready(function() {
                       var base_url=$('#base-url').text();
                       $('#newadjective1').tokenInput(base_url+"/Subjects/adjectives",{ theme: "rtu",hintText: "Type in a search term",tokenLimit:'3'});
                       
                    });
                </script>
                  </tr>
                  
                  <tr>
                  <td width="25%">&nbsp;</td>   <td  colspan="2" ><?php echo $this->Form->end(array('label'=>'','class'=>'submit-btn')); ?></td>
                  </tr>
                </tbody>
              </table>
            
          </div>
    
</div>
<script>
        $(document).ready(function(){
             var base_url=$('#base-url').text();
             $("#autosearch").fancybox({
		'titleShow'     : false,
		'transitionIn'	: 'elastic',
		'transitionOut'	: 'elastic',
		'easingIn'      : 'easeOutBack',
		'easingOut'     : 'easeInBack'
            });
            var inputString=$("#inputString").val();
            
        $("#searchsubjectname").html(inputString);
        $("#subjectname").attr('value',inputString);
        $("#SubjectSearchRateForm").submit(function(){
        //alert($('#error').html());
         var err='0';
         var title=$('input[id=subjectname]').val();
         var specifier=$('input[id=specifier]').val();
         if(title!=''){
            $.ajax({
              url: base_url+"/Homes/subject_suggestion",
              type: "GET",
              data: {"title": title,"specifier": specifier },
              dataType: "json",
              success: function(response){
                           if(response=='1'){
                              $('#subjecterror').fadeIn(100);
                              $('#subjecterror').css("color","red");
                              $('#subjecterror').text('Subject Already Added').delay(5000).fadeOut(1500);
                              err='1';   
                            }else{
                                $('#subjecterror').empty();
                                err='0';
                            }
                        }
                    });
                }
         if($('#image').val()==''){
            $('#missing_image').fadeIn(100);
            $('#missing_image').css("color","red");
            $('#missing_image').text('Upload an Image first.').delay(5000).fadeOut(1500);
            err='1';
        }
     //$('input[name=rating]').val($( "#slider-range-min" ).slider( "value" ));
        if( $('#title').val()==''){
            $('#error').fadeIn(100);
            $('#error').css("color","red");
            $('#error').text('Required').delay(5000).fadeOut(1500);
            err='1';
        }
        if( $('#tagpool').text()==''){
            $('#error-message').fadeIn(100);
             $('#error-message').css("color","red");
            $('#error-message').text('Add atleast one tag to the Subject').delay(5000).fadeOut(1500);
            err='1';
       }
      // alert($('input[name=new-smaill-amount]').val());
        if(err=='1'){
          return false;
        }
        if($('input[name=rating]').val()=='0' || $('input[name=rating]').val()==''){
            if(confirm('Are you sure you want to rate this subject  0 ?')){
                //err='1';
                //return true;
            }else{
                return false;        
            }
        }
        
        if(err=='0'){ 
        var login=false;
         $.ajax({
            url:base_url+'/Homes/check_login',
            async:false,
            success:function(response){
                if(response){
                    login=true;  
                
                }else{
                 $.fancybox({href:'#login_register'});
                 $('.slider-range-min .ui-slider-handle').trigger('click');
                 return false;
                }
            }
        });
            if(!login){
            return false;}
        }        
         //return false;
         //$("#SubjectSearchRateForm").post();
            });
        });
        
    </script>